$cat = {
	load : function(loadAll) {
		$store.get({
			url : '/admin/category/load',
			data : null,
			success : function(d) {
				// refresh categories dropdown
				var select = $('#category-parent');
				select.children().remove();
				var option = $('<option/>');
				option.val(-1).text('[none]');
				select.append(option);

				// refresh the table
				$('#category-table').remove();
				var table = $('#category-table-template').clone();
				table.attr('id', 'category-table');
				table.css('display', 'block').appendTo('#page-root');
				for ( var i = 0; i < d.length; i++) {
					var c = d[i];
					option = $('<option/>');
					option.val(c.id).text(
							c.parentId === -1 ? c.name : '+' + c.name);
					select.append(option);

					var row = table.find('tr.category-row:first').clone();
					row.removeClass('hide');
					table.append(row);
					row.find('td::nth-child(1)').text(c.id);
					row.find('td:nth-child(2)').text(c.name);
					row.find('td:nth-child(3)').text(c.description);
					row.find('td:nth-child(4)').text(c.parentId);
				}
				table.find('tr:odd').css('background-color', '#cabcab');
				$('a[title="edit"]').click(
						function() {
							var $this = $(this).closest('tr');
							$('#category-name').val(
									$this.find('td:nth-child(2)').text());
							$('#category-desc').val(
									$this.find('td:nth-child(3)').text());
							$('#category-parent').val(
									$this.find('td:nth-child(4)').text());
							$('#category-id').val(
									$this.find('td:nth-child(1)').text());
						});
			},
			error : function(e) {
				alert('error loading parent categories');
			}
		});
	},
	save : function() {
		var form = $('#category-form');
		$store.post({
			url : '/admin/category/save',
			data : form.serialize(),
			success : function(d) {
				alert('done');
				$('#category-id').val(null);
				$cat.load(false);
			},
			error : function(e) {
				alert('error');
			}
		});
	}
};
$(document).ready(function() {
	$cat.load(true);
	$('#save-category-button').click(function() {
		$cat.save();
	});
	$('#reset-category-button').click(function() {
		$('#category-id').val(null);
	});
});